package com.test.list.adapter;

/** Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Filter;
import android.widget.ImageView;
import android.widget.TextView;

import com.test.list.R;
import com.test.list.activity.ContactsActivity;
import com.test.list.classes.ViewableList;
import com.test.list.contacts.ContactMngr;
import com.test.list.imageLoading.ImageLoader;
import com.test.list.interfaces.Viewable;
import com.test.list.simple.Controller;

public class AmazingLazyAdapter extends AmazingAdapter
{
	private List<Pair<String, List<Viewable>>> mData;
	public ImageLoader mImageLoader;
	private static LayoutInflater mInflater = null;
	private List<Viewable> mViewables;
	private Integer mLayoutType;

	public void refreshAll()
	{
		mData = getAllContactData();
	}

	// public AmazingLazyAdapter(Activity act, List<Contact> contacts)
	// {
	// super(act, contacts);
	// }

	/**
	 * 
	 * @param act
	 * @param contacts
	 */
	public AmazingLazyAdapter(Activity act, List<Viewable> contacts)
	{
		super(act, R.layout.list_item_w, contacts);

		mViewables = contacts;

		initiateLayout(act, R.layout.list_item_w);// , R.layout.contact_item_b);
	}

	/**
	 * 
	 * @param act
	 * @param contacts
	 * @param mainLayoutType
	 * @param secondaryLayoutType
	 */
	public AmazingLazyAdapter(Activity act, List<Viewable> contacts,
			Integer mainLayoutType)// , Integer secondaryLayoutType)
	{
		super(act, mainLayoutType, contacts);

		setViewables(contacts);
		initiateLayout(act, mainLayoutType);// , secondaryLayoutType);
	}

	/**
	 * 
	 * @param act
	 * @param mainLayoutType
	 * @param secondaryLayoutType
	 */
	private void initiateLayout(Activity act, Integer mainLayoutType)
	{
		mLayoutType = mainLayoutType;
		mInflater = (LayoutInflater) act
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mImageLoader = new ImageLoader(act);

	}

	final Filter mFilter = new Filter()
	{
		@Override
		protected FilterResults performFiltering(CharSequence constraint)
		{
			ContactMngr contactMngr = ContactMngr.getInstance();
			List<Viewable> filteredContactResults = new ViewableList()
					.getViewables();
			if (constraint.toString().equals(ContactsActivity.sLOCK))
			{

				filteredContactResults = contactMngr.getContacts(
						constraint.toString()).getViewables();
			}
			FilterResults results = new FilterResults();
			results.values = filteredContactResults;

			return results;

		}

		@SuppressWarnings("unchecked")
		@Override
		protected void publishResults(CharSequence constraint,
				FilterResults results)
		{

			if (constraint != null
					&& constraint.toString().equals(ContactsActivity.sLOCK))
			{
				setViewables((List<Viewable>) results.values);
				refreshAll();
				notifyDataSetChanged();
			}
		}

	};

	@Override
	public Filter getFilter()
	{
		return mFilter;
	}

	@Override
	public View getAmazingView(int position, View convertView, ViewGroup parent)
	{
		ViewHolder viewHolder;
		viewHolder = new ViewHolder();
		if (convertView == null)
		{

			convertView = getInflater().inflate(getMainLayout(), null);
			viewHolder.image = (ImageView) convertView.findViewById(R.id.image);
			viewHolder.text = (TextView) convertView.findViewById(R.id.text);
			convertView.setTag(viewHolder);
		} else
		{
			viewHolder = (ViewHolder) convertView.getTag();
		}

		viewHolder.text.setText(getContacts().get(position).getMainHeader());

//		mImageLoader.DisplayImage(getContacts().get(position)
//				.getMainPictureID(), viewHolder.image);
		
		mImageLoader.DisplayImage(getContacts().get(position), viewHolder.image);

		return convertView;
	}

	static class ViewHolder
	{
		protected TextView text;
		protected ImageView image;
	}

	@Override
	protected void bindSectionHeader(View view, int position,
			boolean displaySectionHeader)
	{
		if (displaySectionHeader)
		{
			view.findViewById(R.id.header).setVisibility(View.VISIBLE);
			TextView lSectionTitle = (TextView) view.findViewById(R.id.header);
			lSectionTitle
					.setText(getSections()[getSectionForPosition(position)]);
		} else
		{
			view.findViewById(R.id.header).setVisibility(View.GONE);
		}
	}

	@Override
	public void configurePinnedHeader(View header, int position, int alpha)
	{
		TextView lSectionHeader = (TextView) header;
		lSectionHeader.setText(getSections()[getSectionForPosition(position)]);
		lSectionHeader.setBackgroundColor(alpha << 24 | (0xbbffbb));
		lSectionHeader.setTextColor(alpha << 24 | (0x000000));
	}

	@Override
	public int getPositionForSection(int section)
	{
		if (section < 0)
		{
			section = 0;
		}
		if (section >= mData.size())
		{
			section = mData.size() - 1;
		}
		int c = 0;
		for (int i = 0; i < mData.size(); i++)
		{
			if (section == i)
			{
				return c;
			}
			c += mData.get(i).second.size();
		}
		return 0;
	}

	@Override
	public int getSectionForPosition(int position)
	{
		int c = 0;
		for (int i = 0; i < mData.size(); i++)
		{
			if (position >= c && position < c + mData.get(i).second.size())
			{
				return i;
			}
			c += mData.get(i).second.size();
		}
		return -1;
	}

	@Override
	public String[] getSections()
	{
		String[] res = new String[mData.size()];
		for (int i = 0; i < mData.size(); i++)
		{
			res[i] = mData.get(i).first;
		}
		return res;
	}

	/**
	 * 
	 * @return
	 */
	public List<Pair<String, List<Viewable>>> getAllContactData()
	{
		List<Pair<String, List<Viewable>>> retVal = new ArrayList<Pair<String, List<Viewable>>>();

		List<Viewable> cs = getContacts();
		List<Viewable> tempContacts = null;
		if (cs != null)
		{
			String name;
			char lastChar = '^';
			for (Viewable viewable : cs)
			{
				name = viewable.getMainHeader();
				if (lastChar != name.charAt(0))
				{
					lastChar = name.charAt(0);
					tempContacts = new ArrayList<Viewable>();
					retVal.add(new Pair<String, List<Viewable>>(lastChar + "",
							tempContacts));
				}
				tempContacts.add(viewable);
			}
		}

		return retVal;
	}

	/**
	 * 
	 * @return
	 */
	public Integer getMainLayout()
	{
		return mLayoutType;
	}

	/**
	 * 
	 * @return
	 */
	public LayoutInflater getInflater()
	{
		return mInflater;
	}

	/**
	 * 
	 * @return
	 */
	public List<Viewable> getContacts()
	{
		return mViewables;
	}

	@Override
	public int getCount()
	{
		if (mViewables == null)
			return 0;
		return mViewables.size();
	}

	/**
	 * 
	 * @param contacts
	 */
	public void setViewables(List<Viewable> viewables)
	{
		mViewables = viewables;
	}

	/**
	 * 
	 */
	@Override
	public void hideKeyboard()
	{
		Controller.getInstance().hideKeyboard();

	}

	/**
	 * 
	 */
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState)
	{
		hideKeyboard();
	}

}